package com.example.md.controller;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.example.md.common.Result;
import com.example.md.dto.markdown.SaveMarkdownReqDTO;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;

@RestController
@RequestMapping("/md")
public class MarkdownController {
    
    @Value("${md_dir}")
    public String markdownDir;

    @GetMapping("/")
    public Result<String> getMethodName(@RequestParam("path") String path) {
        if (StrUtil.isBlank(path)) {
            return Result.failed("Missing \"path\" query parameter");
        }

        String filePath = StrUtil.builder().append(markdownDir).append(File.separator).append(path).toString();
        // 验证文件是否存在
        if (!FileUtil.exist(filePath)) {
            return Result.failed("File not found");
        }
        List<String> contents = FileUtil.readLines(new File(filePath), "UTF-8");
        String result = StrUtil.join(System.lineSeparator(), contents);

        return Result.success(result);
    }

    @PostMapping("/image/upload")
    public Result<Map<String, Object>> uploadImage(@RequestParam("file") MultipartFile file, @RequestParam("path") String path) throws IOException {
        String originFilename = file.getOriginalFilename();
        String extension = FileUtil.extName(originFilename);

        // 定义文件唯一标识码
        String UUID = IdUtil.fastSimpleUUID();
        // 构造 唯一 的文件名​
        String finalFileName = UUID + StrUtil.DOT + extension;

        // 获取相对路径 ./xxx
        Integer separatorIndex = path.lastIndexOf(File.separator);
        String relativePath = path.substring(0, separatorIndex);

        String imageFileDir = StrUtil.builder().append(markdownDir).append(File.separator).append(relativePath).append(File.separator).append("images").toString();
        if (!FileUtil.exist(imageFileDir)) {
            FileUtil.mkdir(imageFileDir);
        }
        System.out.println("上传目录​：" + imageFileDir);
        String imageFilePath = StrUtil.builder().append(imageFileDir).append(File.separator).append(finalFileName).toString();
        System.out.println("上传文件​：" + imageFilePath);    

        file.transferTo(new File(imageFilePath));

        Map<String, Object> result = new HashMap<>();
        String url = StrUtil.builder().append(StrUtil.DOT).append(File.separator).append("images").append(File.separator).append(finalFileName).toString();
        result.put("url", url);

        return Result.success(result);
    }

    @PostMapping("/save")
    public Result<Boolean> saveMarkdown(@RequestBody @Validated SaveMarkdownReqDTO requestBody) {
        String path = requestBody.getPath();
        String content = requestBody.getContent();

        String filePath = StrUtil.builder().append(markdownDir).append(File.separator).append(path).toString();
        // 验证文件是否存在
        if (!FileUtil.exist(filePath)) {
            return Result.failed("File not found");
        }
        FileUtil.writeUtf8String(content, new File(filePath));

        return Result.success(true);
    }
}
